package com.spring.cloud.lb;

import lombok.extern.apachecommons.CommonsLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: Admin
 * @Date: 2021/3/19 11:00
 * @Description:
 */
@Component
@Slf4j
public class RoundRobbinLB implements LoadBalance {


    // 访问次数
    private AtomicInteger account = new AtomicInteger(0);

    private int incrementAndGetInt() {

        int current = 0;

        int next = 0;

        do {
            current = account.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!account.compareAndSet(current, next));

        log.info("next:" + next);
        return next;

    }


    @Override
    public ServiceInstance instance(List<ServiceInstance> instances) {
        return instances.get(incrementAndGetInt() % instances.size());
    }
}
